import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '../store/user'
import cookie from 'js-cookie'
import { authorization } from '../config/cacheKey'

var userStore

let routes = []
// 导入所有路由配置模块
const routeModules = import.meta.globEager('./routes/*.js')
for (const path in routeModules) {
  routes = routes.concat(routeModules[path].default)
}

const router = createRouter({
  // hash模式
  history: createWebHashHistory(),
  routes: routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (!userStore) {
    userStore = useUserStore()
  }
  if (to.name === 'Login') {
    next()
  } else if (userStore.token) {
    next()
  } else if (cookie.get(authorization)) {
    userStore.setToken(cookie.get(authorization))
    next()
  } else {
    next({
      path: '/login',
      query: { redirect: to.fullPath },
      replace: true
    })
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
